package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Watchable;
import java.util.HashMap;
import java.util.Map;

public class HttpServletRequest {
    private Socket socket;

    private String method;
    private String uri;
    private String requestURI;
    private String queryString;
    private Map<String, String> parameters = new HashMap<>();
    private String protocol;

    private Map<String, String> headers = new HashMap<>();


    public HttpServletRequest(Socket socket) throws IOException, EmptyRequestException {
        Thread thread =Thread.currentThread();
        System.out.println("33333333333333333333333当前线程为："+thread+"333333333333333333333333333333");

        this.socket = socket;
        parseRequestLine();
        parseHeaders();
        parseContent();

    }

    private void parseRequestLine() throws IOException, EmptyRequestException {


        String line = readLine();
        if (line.isEmpty()){
            throw new EmptyRequestException();
        }
       // line = URLDecoder.decode(line,"UTF-8");
//        if(line.isEmpty()){
//            throw new
//        }
        String[] array = line.split("\\s");
        method = array[0];
        uri = array[1];
        paseURI();
        protocol = array[2];
        System.out.println("请求方式method为:"+method);
        System.out.println("抽象路径为:"+uri);
        System.out.println("协议版本为:"+protocol);
    }

    private void paseURI() {
        String[] data = uri.split("\\?");
        requestURI = data[0];
        if (data.length > 1) {
            queryString = data[1];
//            data = queryString.split("&");
//            for (String e : data) {
//                String[] array = e.split("=");
//                parameters.put(array[0], array.length > 1 ? array[1] : null);
//            }
            parsrParameter(queryString);

        }
        System.out.println("requestURI:" + requestURI);
        System.out.println("queryString:" + queryString);
        System.out.println("parameters:" + parameters);
    }

    private void parseHeaders() throws IOException {
        while (true){
            String line=readLine();
            if (line.isEmpty()){
                break;
            }
            String[] array= line.split(":\\s");
            headers.put(array[0],array[1]);

        }
        System.out.println("headers:" + headers);
    }

    private void parseContent() throws IOException {
        if ("POST".equals(method)){

            if(headers.containsKey("Content-Length")){
               int contentLength =Integer.parseInt (headers.get("Content-Length"));
               byte[] data= new byte[contentLength] ;
               InputStream in  =socket.getInputStream();
               in.read(data );
               if(headers.containsKey("Content-Type")){
                  if ("application/x-www-form-urlencoded".equals(headers.get("Content-Type"))){
                      String line= new String(data, StandardCharsets.ISO_8859_1);
                    parsrParameter(line);
                      System.out.println(getparameter("username"));
                      System.out.println(getparameter("password"));
                      System.out.println(getparameter("nickname"));
                      System.out.println(getparameter("agestring"));
                  }
               }
            }




        }
    }
    private void parsrParameter(String line){

        try {
            line= URLDecoder.decode(line,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String[] array =line.split("&");
        for (String e :array){
            String []array1= e.split("=");
            parameters.put(array1[0],array1.length>1? array1[1]:null);

        }
    }

    private String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        int len;
        char pre = 'a';
        char cur = 'a';
        StringBuilder builder = new StringBuilder();
        while ((len = in.read()) != -1) {
            cur = (char) len;
            if (pre == 13 && cur == 10) {
                break;
            }
            builder.append(cur);
            pre = cur;

        }
        return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getRequestURI() {
        return requestURI;
    }

    public String getQueryString() {
        return queryString;
    }

    public String getProtocol() {
        return protocol;
    }
    public String getHeader(String name){
        return  headers.get(name);
    }
    public String getparameter(String name){
        return  parameters.get(name);
    }

}
